<template>
    <div class="flex-box flex-column page">
        <div class="scroll-container flex1">
            <div v-if="contacts.length === 0" class="empty-tips">
                <div class="empty-icon">📭</div>
                <div class="empty-text">当前通讯录为空，请点击下方按钮导入数据</div>
            </div>
            <div v-show="contacts.length" class="contact-list">
                <div v-for="(contact, index) in filteredContacts" :key="index" class="contact-item flex-box flex-acenter">
                    <div class="contact-field flex2">序号：{{ index + 1 }}</div>
                    <div class="contact-field copy flex2">姓名：{{ contact.姓名 || '未填写' }}</div>
                    <div class="contact-field copy flex3">电话：{{ contact.电话 || '未填写' }}</div>
                    <div class="contact-field flex3">职位：{{ contact.职位 || '未填写' }}</div>
                    <div class="contact-field flex4">邮箱：{{ contact.邮箱 || '未填写' }}</div>
                    <div class="contact-actions">
                        <button @click="handleEdit(index)" class="edit-btn">修改</button>
                        <button @click="handleDelete(index)" class="delete-btn">删除</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="management flex-box flex-acenter">
            <button class="btn-management" @click="handleUpload">上传通讯录</button>
            <button class="btn-management" @click="handleDownload">下载全部</button>
            <button class="btn-management" @click="handleDeleteAll">全部删除</button>
            <input type="file" ref="fileInput" @change="handleFileChange" hidden />
        </div>
    </div>
    <van-popup v-model:show="showPopup" :style="{ padding: '20px' }">
        <div class="popup-content">
            <van-field v-model="tempData.姓名" label="姓名" placeholder="请输入姓名" />
            <van-field v-model="tempData.电话" label="电话" type="tel" placeholder="请输入电话" />
            <van-field v-model="tempData.职位" label="职位" placeholder="请输入职位" />
            <van-field v-model="tempData.邮箱" label="邮箱" type="email" placeholder="请输入邮箱" />
            <div class="flex-box flex-jaround" style="padding: 20px 0 0">
                <button @click="confirmEdit" class="confirm-btn">确认修改</button>
                <button @click="showPopup = false" class="cancel-btn">取消</button>
            </div>
        </div>
    </van-popup>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { showDialog, showConfirmDialog } from 'vant';
import pinyin from 'pinyin';
import * as XLSX from 'xlsx';

const showPopup = ref(false);
const tempData = ref({});
const editingIndex = ref(-1);

const contacts = ref([]);
const fileInput = ref(null);
const loading = ref(false);
const errorMessage = ref('');
const searchKeyword = ref('');

onMounted(() => {
    loadContacts();
});

const handleDeleteAll = () => {
    showConfirmDialog({
        title: '确认删除全部',
        message: '确定要删除所有联系人？此操作不可恢复！'
    })
        .then(() => {
            contacts.value = [];
            saveContacts();
        })
        .catch(() => {
            // 取消操作
        });
};

const confirmEdit = () => {
    contacts.value[editingIndex.value] = tempData.value;
    saveContacts();
    showPopup.value = false;
};

const handleEdit = (index) => {
    // 获取原始数据中的真实索引
    const realIndex = contacts.value.findIndex((c) => c === filteredContacts.value[index]);
    editingIndex.value = realIndex;
    tempData.value = { ...contacts.value[realIndex] };
    showPopup.value = true;
};

const handleDelete = (index) => {
    // 获取原始数据中的真实索引
    const realIndex = contacts.value.findIndex((c) => c === filteredContacts.value[index]);

    showConfirmDialog({
        title: '确认删除',
        message: '确定要删除该联系人？'
    })
        .then(() => {
            contacts.value.splice(realIndex, 1);
            saveContacts();
        })
        .catch(() => {
            // 取消操作
        });
};

const saveContacts = async () => {
    const existingDoc = await window.utools.db.promises.get('contacts').catch(() => null);
    await window.utools.db.promises.put({
        _id: 'contacts',
        _rev: existingDoc?._rev,
        data: JSON.parse(JSON.stringify(contacts.value)), // Add JSON sanitization
        updated: Date.now()
    });
    console.log('联系人保存成功');
};

const loadContacts = async () => {
    // 从数据库读取联系人数据
    try {
        const doc = await window.utools.db.promises.get('contacts');
        if (doc && doc.data) {
            contacts.value = doc.data;
            console.log('数据库读取成功:', doc);
        } else {
            console.log('数据库无联系人数据');
        }
    } catch (err) {
        console.error('数据读取失败:', err);
    }
};

const filteredContacts = computed(() => {
    if (!searchKeyword.value) {
        return contacts.value;
    }

    const kw = searchKeyword.value.toLowerCase();
    const isPhoneSearch = /^\d+$/.test(kw);
    const isInitialsSearch = /^[a-z]+$/.test(kw);

    return contacts.value.filter((contact) => {
        if (isPhoneSearch) {
            return String(contact.电话 || '')
                .toLowerCase()
                .includes(kw);
        }

        if (isInitialsSearch) {
            const name = contact.姓名 || '';
            const initials = pinyin(name, {
                style: pinyin.STYLE_FIRST_LETTER, // 精确到每个字的首字母
                heteronym: false // 关闭多音字模式
            })
                .flat()
                .join('')
                .toLowerCase();
            return initials.startsWith(kw);
        }

        return [contact.姓名, contact.职位].some((field) =>
            String(field || '')
                .toLowerCase()
                .includes(kw)
        );
    });
});

utools.setSubInput(({ text }) => {
    searchKeyword.value = text;
}, '搜索');

const handleUpload = () => {
    fileInput.value.click();
};

const handleFileChange = async (e) => {
    loading.value = true;
    errorMessage.value = '';
    const file = e.target.files[0];
    if (file) {
        try {
            const arrayBuffer = await file.arrayBuffer();
            // const decoder = new TextDecoder('gb18030');
            // const csvData = decoder.decode(arrayBuffer);

            const workbook = XLSX.read(arrayBuffer, {
                type: 'array',
                cellDates: true,
                cellText: false,
                raw: true
            });

            const sheet = workbook.Sheets[workbook.SheetNames[0]];
            const newContacts = XLSX.utils
                .sheet_to_json(sheet)
                // 表格内去重（保留第一个出现的记录）
                .filter((contact, index, self) => index === self.findIndex((c) => String(c.电话 || '').trim() === String(contact.电话 || '').trim()))
                // 数据库去重
                .filter((newContact) => !contacts.value.some((existing) => String(existing.电话 || '').trim() === String(newContact.电话 || '').trim()));
            contacts.value.push(...newContacts);
            console.log('解析后的联系人:', contacts.value); // 控制台日志
            // 添加保存结果验证

            // 深度清洗数据（处理特殊格式）
            const sanitizedData = contacts.value.map((contact) => {
                return Object.fromEntries(
                    Object.entries(contact).map(([key, value]) => {
                        // 基础类型处理
                        if (value instanceof Date) {
                            return [key, value.toISOString().split('T')[0]];
                        }
                        if (typeof value === 'string') {
                            return [key, value.trim()];
                        }
                        return [key, value];
                    })
                );
            });
            const existingDoc = await window.utools.db.promises.get('contacts').catch(() => null);

            const result = await window.utools.db.promises.put({
                _id: 'contacts',
                _rev: existingDoc?._rev, // 添加修订版本号
                data: sanitizedData,
                updated: new Date().getTime()
            });

            // 确保日志执行并添加错误边界检查
            if (result) {
                console.log('保存结果:', result); // 保留原有日志
            } else {
                console.log('保存返回结果为空');
            }
        } catch (err) {
            console.log('保存过程发生错误:', err); // 添加错误日志
            showDialog({
                message: '文件格式错误：请上传有效的xls/xlsx文件'
            }).then(() => {
                // on close
            });
        }
    }
    loading.value = false;
    e.target.value = ''; // 清空文件选择器
};

const handleDownload = () => {
    // 创建工作表
    const data =
        contacts.value.length > 0
            ? contacts.value.map((c) => ({
                  姓名: c.姓名 || '',
                  电话: c.电话 || '',
                  职位: c.职位 || '',
                  邮箱: c.邮箱 || ''
              }))
            : [];

    const worksheet = contacts.value.length ? XLSX.utils.json_to_sheet(data) : XLSX.utils.aoa_to_sheet([['姓名', '电话', '职位', '邮箱']]);

    // 创建工作簿
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '联系人');

    // 生成Excel文件
    const excelBuffer = XLSX.write(workbook, {
        bookType: 'xlsx',
        type: 'array'
    });

    // 创建Blob并下载
    const blob = new Blob([excelBuffer], { type: 'application/octet-stream' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `contacts_${new Date().toISOString().slice(0, 10)}.xlsx`;
    link.click();
    URL.revokeObjectURL(url);
};
</script>

<style scoped>
.page {
    height: 100vh;
}

.scroll-container {
    overflow: hidden;
    padding: 0 0 0 10px;
}

.contact-list {
    overflow-y: auto;
    height: 100%;
}

.contact-item {
    padding: 5px;
    border-bottom: 1px solid #eee;
}

.contact-actions button {
    margin-left: 8px;
    padding: 6px 12px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.management {
    background-color: #eee;
    height: 50px;
    padding: 0 10px;
}

.btn-management {
    margin: 0 10px 0 0;
    padding: 0 8px;
    background: #28a745;
    color: white;
    border: none;
    border-radius: 4px;
    font-size: 12px;
}

.popup-content .confirm-btn {
    width: 100px;
    border-radius: 4px;
}

.popup-content .cancel-btn {
    width: 110px;
    border-radius: 4px;
}

.empty-tips {
    padding: 40px 20px;
    text-align: center;
    color: #888;
}
.empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
}
.empty-text {
    font-size: 14px;
}
</style>
